package ua.com.minus1.lookbattle.net;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import ua.com.minus1.lookbattle.models.CommonResult;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Created with IntelliJ IDEA.
 * User: Flash
 * Date: 10.07.12
 * Time: 16:20
 * To change this template use File | Settings | File Templates.
 */
public class MultipartUploader {
    private DefaultHttpClient mHttpClient;
    private ExecutorService executorService;

    public MultipartUploader() {
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        mHttpClient = new DefaultHttpClient(params);
    }

    private ExecutorService getExecutorService() {
        if(executorService == null)
            executorService = Executors.newFixedThreadPool(5);
        return executorService;
    }

    public Future uploadLook(Context context, String uid, int catId, int countryId, File image, HttpManager.HttpResultHandler<CommonResult> handler) {
        return getExecutorService().submit(new ImageUploader(context, uid, catId, countryId, image, handler));
    }

    private class ImageUploader implements Runnable{
        private Context context;
        private final String uid;
        private final int catId;
        private int countryId;
        private final File image;
        private HttpManager.HttpResultHandler<CommonResult> handler;

        private ImageUploader(Context context, String uid, int catId, int countryId, File image, HttpManager.HttpResultHandler<CommonResult> handler) {
            this.context = context;
            this.uid = uid;
            this.catId = catId;
            this.countryId = countryId;
            this.image = image;
            this.handler = handler;
        }

        public void run() {
            HttpPost httpPost = new HttpPost(URLManager.getUploadLookURL());

            try {
                MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                multipartEntity.addPart("aid", new StringBody(uid));
                multipartEntity.addPart("c", new StringBody(String.valueOf(catId)));
                multipartEntity.addPart("cnt", new StringBody(String.valueOf(countryId)));
                multipartEntity.addPart("look", new FileBody(image));
                httpPost.setEntity(multipartEntity);

                HttpResponse response = mHttpClient.execute(httpPost);

                if (Thread.currentThread().isInterrupted())
                    return;

                CommonResult result = null;
                if (response.getStatusLine().getStatusCode() == 200) {
                    Gson gson = new Gson();
                    result = gson.fromJson(new InputStreamReader(response.getEntity().getContent()), CommonResult.class);
                    Log.i(MultipartUploader.class.getName(), "image upload result: " + result.toString());
                }

                if (Thread.currentThread().isInterrupted())
                    return;

                final CommonResult commonResult = result;
                ((Activity) context).runOnUiThread(new Runnable() {
                    public void run() {
                        handler.onResultLoadComplete(commonResult);
                    }
                });

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

